
import React, { Component } from 'react';
import {
    StyleSheet, Text, FlatList, Animated, View, Image, Alert, TouchableOpacity, Dimensions
} from "react-native";
import { NavigationEvents, ScrollView } from 'react-navigation';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import ToastUtil from '../../../utils/toast';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import { STORAGE_CONSTANT } from '../../../config/storage';
import StorageHelper from '../../../utils/storageHelper';
import { Common } from '../../../component/common/Common.js';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { ProgressModal } from '../../../components/common/ProgressModal';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ResourceOfferCard } from '../_components/resourceOfferCard';
import { ResourceBaseInfoCard } from '../_components/resourceBaseInfoCard';
import { OfferCommon } from '../_common/common';
import { CommonDialog } from '../../../components/common/Dialog';
import ModalPicsComponent from '../../customer-management/enterprise/details/_components/ModalPicsComponent';
const scale = GLOBAL.SCALE;
const arrowIcon = require('../../../imgs/order/down.png')
const modalPicDelCfg = {
    visible: false,
    urls: [],
    picPress: () => { },
}

export class OfferApproveDetail extends Component {
    static navigationOptions = ({ navigation, navigationOptions }) => {
        return {
            headerTitle: '资源详情',
            headerTintColor: style.color.white,
            headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
            headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
            headerStyle: style.head.headerStyle,
            headerTitleStyle: {
                flex: 1,
                textAlign: 'center',
            }
        }
    };

    constructor(props) {
        super(props);
        console.log('OfferApproveDetail-props', this.props.navigation.state.params)
        this.state = {
            modalVisible: false,
            remarkModalVisible: false,
            status: 'loading',
            statusLit: 'data',
            resDetail: {},
            itemData: {},
            lightBoxData: {
                modalVisible: false,
                onClosePress: this._closeLightBox,
                title: [{
                    value: '审批',
                    key: 'APPROVE',
                    onPress: (key) => this._lightBoxTitlePress(key),
                }, {
                    value: '操作',
                    key: 'ACTIVE',
                    onPress: (key) => this._lightBoxTitlePress(key),
                }],
                rowDataList: [],
                hideAuditResultName: false
            },
            approveList: [],
            activeList: [],
            previewModalVisible: false
        }
        let { data, pageFrom } = this.props.navigation.state.params;
        let { bidPackageApplyId, periodNum, bizModel, periodSeq } = data || {};
        this.pageFrom = pageFrom;
        this.pageParams = {
            bidPackageApplyId,
            periodNum,
            bizModel,
            periodSeq
        }
    }

    async componentWillMount() {
        this.userInfo = await this._getUserInfo();
        await this.initPage();
    }

    _getUserInfo = async () => {
        //获取用户信息
        let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
        if (userInfo) {
            userInfo = JSON.parse(userInfo);
        }
        return userInfo || {};
    }

    //初始化数据
    initPage = async (refreshIcon) => {
        this.setState({
            status: 'loading'
        })
        //审批详情vs资源详情 定为同一个接口
        let res = await HTTP.POST(API_GENERATE(API.PACKAGE_APPLY_PERIOD_DETAIL), this.pageParams);
        if (res) {
            res = this.getRequireParams(res);
            const { packageApplyGoodsTOS, bizModel, bizModelName } = res || {};
            packageApplyGoodsTOS && packageApplyGoodsTOS.length && packageApplyGoodsTOS.map((item, index) => {
                item.bizModel = bizModel;
                item.bizModelName = bizModelName;
            })
            this.setState({
                resDetail: res,
                status: 'data'
            })
        } else {
            this.setState({
                status: 'error'
            })
        }
    }
    // 返回值数据补充
    getRequireParams = (res) => {
        let { packageApplyGoodsTOS } = res || {};
        if (packageApplyGoodsTOS && packageApplyGoodsTOS.length > 0) {
            packageApplyGoodsTOS.forEach(item => {
                item.showItem = false;
                item.boxHeight = new Animated.Value(item.resourceApplyList && item.resourceApplyList.length >= 2 ? 224 * scale : 112 * scale);
                item.openHeight = 0;
                if (item.resourceApplyList && item.resourceApplyList.length > 0) {
                    item.openHeight = 112 * item.resourceApplyList.length
                } else {
                    item.resourceApplyList = []
                }
            })
        }
        return res
    }

    // 同意
    auditPress = (type, item) => {
        this.auditResult = type;
        this.remark = '';
        if (item) {
            this.setState({
                showRejectModal: true,
                itemData: item,
            })
        } else {
            ToastUtil.showWarning('没有数据')
        }
    }

    // 审批
    approve = async () => {
        let { resDetail } = this.state;
        let { salesType, corpId, bizModelName, processInstanceId } = resDetail || {};
        let { data } = this.props.navigation.state.params;
        if (!this.auditResult && (!this.remark || !this.remark.length)) {
            Alert.alert('请输入驳回意见')
            return;
        }
        let requestParams = {
            businessKey: data.businessKey,
            taskId: data.taskId,
            formKey: data.formKey,
            remark: this.remark,
            auditResult: this.auditResult,
            corpId,
            salesType,
            bizModelName,
            processInstanceId
        };
        let text = this.auditResult ? '审批' : '驳回';
        this.setState({
            showRejectModal: false,
            status: 'loading'
        })
        let res = await HTTP.POST(API_GENERATE(API.PACKAGE_APPLY_AUDIT), requestParams);
        if (res) {
            ToastUtil.showSuccess(`${text}成功`).then(() => {
                navigationSeevice.navigate('OfferApproveList', { salesType })
            })
        } else {
            this.setState({
                status: 'data'
            })
        }
    }

    async getImgView(qualificationAddress) {
        // qualificationAddress = ['21030414520490432116635129', '21030414521970372390151129', '20101910105875619913315129']
        if (qualificationAddress.length === 1) {
            this.setState({
                statusLit: 'loading'
            }, () => {
                qualificationAddress.map(async (fileId) => {
                    await this.loadedImgs(fileId);
                })
            })
        }
        else {
            this.props.navigation.navigate('Attachment', { qualificationAddress })
        }
    }
    async loadedImgs(fileId) {
        const response = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId });
        if (response && response.image && response.image.length) {
            modalPicDelCfg.visible = true;
            modalPicDelCfg.urls.push({
                url: response.image,
                width: Dimensions.get('window').width
            });
            modalPicDelCfg.picPress = () => {
                modalPicDelCfg.visible = false;
                modalPicDelCfg.urls = [];
                this.setState({
                    previewModalVisible: false,
                });
            }
        }
        this.setState({
            statusLit: 'data',
            previewModalVisible: true
        });
    }

    // 查看审批流
    _getCheckApprove = async (item) => {
        let { resDetail } = this.state;
        let { corpId, processInstanceId } = resDetail || {};
        //查询审批节点
        let responseData1 = await HTTP.GET(API_GENERATE(API.PACKAGE_APPLY_AUDIT_LOG), {
            bizObjType: 'PACKAGE_OFFER',
            processInstanceId,
            bizId: item.bidPackageApplyId,
            corpId
        });
        responseData1 = responseData1 && responseData1.map((item) => {
            if (item.auditResult == 9) {
                item.auditResultName = '操作';
            }
            return item;
        })
        //操作日志
        let responseData2 = await HTTP.POST(API_GENERATE(API.PACKAGE_APPLY_OPERATION_LOG), {
            bidPackageApplyId: item.bidPackageApplyId,
        });
        let { lightBoxData } = this.state;
        lightBoxData.modalVisible = true;
        lightBoxData.rowDataList = responseData1;
        // lightBoxData.hideAuditResultName = false;
        this.setState({
            activeList: responseData2,
            approveList: responseData1,
            lightBoxData,
            status: 'data'
        })
    }

    _lightBoxTitlePress(key) {
        let { lightBoxData, approveList, activeList } = this.state;
        lightBoxData.rowDataList = key == 'APPROVE' ? approveList : activeList;
        lightBoxData.hideAuditResultName = key == 'APPROVE' ? false : true;
        this.setState({
            lightBoxData
        })
    }

    _closeLightBox = () => {
        let { lightBoxData } = this.state;
        lightBoxData.modalVisible = false;
        this.setState({ lightBoxData });
    }

    _bizModelAction = async (type, item) => {
        const { bidPackageApplyId, bidPackageId, status, isFirstPeriod } = item;
        let { resDetail } = this.state;
        let { salesType, bizModel, processInstanceId, periodNum } = resDetail || {};
        //撤销本轮
        if (type.type == 'CANCEL') {
            this._AlertOk('CANCEL', '撤销本轮', { bidPackageApplyId, processInstanceId, status });
        }
        //删除
        if (type.type == 'DELETE') {
            this._AlertOk('DELETE', '删除', { bidPackageApplyId });
        }
        //提交
        if (type.type == 'SUBMIT') {
            navigationSeevice.navigate('OfferCreatePage', { salesType, bidPackageApplyId });
        }
        //重新提交-首轮OfferCreatePage，非首轮OneRoundPage
        if (type.type == 'RESUBMIT') {
            const goPage = bizModel == 'M' ? (isFirstPeriod == 'Y' ? 'OfferCreatePage' : 'OneRoundPage') : 'OfferCreatePage';
            navigationSeevice.navigate(goPage, { salesType, bidPackageApplyId, notFirst: isFirstPeriod == 'Y' ? false : true });
        }
        //再来一轮 跳转再来一轮页面
        if (type.type == 'READD') {
            navigationSeevice.navigate('OneRoundPage', { salesType, bidPackageApplyId, });
        }
        //查看报盘 跳转查看报盘页面
        if (type.type == 'CHECK') {
            navigationSeevice.navigate('OfferSituation', { bidPackageId, salesType, bizModel, periodNum, listData: { ...this.props.navigation.state.params } });
        }
    }

    //删除和撤销弹出框提示
    _AlertOk = (type, text, params) => {
        let { resDetail } = this.state;
        let { salesType, bizModel, packageApplyGoodsTOS } = resDetail || {};
        Alert.alert('提示', `确定${text}吗?`, [
            {
                text: '确认', onPress: async () => {
                    this.setState({ status: 'loading' });
                    const api = type == 'CANCEL' ? API.PACKAGE_APPLY_CANCEL : API.PACKAGE_APPLY_DELETE;
                    const res = await HTTP.POST(API_GENERATE(api), params);
                    if (res) {
                        this.setState({ status: 'data' });
                        ToastUtil.showSuccess(`${text}成功`).then(() => {
                            //多轮&&多轮&&删除 or 撤销 => 刷新详情页
                            if (type == 'CANCEL' || (bizModel == 'M' && type == 'DELETE' && packageApplyGoodsTOS.length > 1)) {
                                //删除之后取最新一轮的bidPackageApplyId刷新
                                this.pageParams.bidPackageApplyId = type == 'DELETE' ? packageApplyGoodsTOS[1].bidPackageApplyId : this.pageParams.bidPackageApplyId;
                                this.initPage();
                            } else {
                                //删除返回列表
                                navigationSeevice.navigate('OfferList', { salesType });
                            }
                        })
                    } else {
                        this.setState({ status: 'data' });
                    }
                }
            },
            {
                text: '取消', onPress: () => { console.log('取消', text) }
            },
        ]);
    }

    _approvalListItim = (item) => {
        let { resDetail } = this.state;
        let { packageApplyGoodsTOS, salesType } = resDetail || {};
        return (
            <ResourceOfferCard
                showStatus={true}
                itemForDetail={true}
                salesType={salesType}
                listData={packageApplyGoodsTOS}
                itemData={item}
                renderBottomComponent={this._renderBottomComponent(item.item)}
                checkApproveList={() => this._getCheckApprove(item.item)}
                getImgView={() => this.getImgView(item.item.fileIdArry)}
                resetListData={(resetListData) => {
                    packageApplyGoodsTOS = resetListData;
                    this.setState({ resDetail })
                }} />
        )
    }

    _renderClinch = (data) => {
        let { salesType, periodNum, winRule, bizModel, canBargainApply, bidPackageId } = data || {};
        if (bizModel === 'M' && canBargainApply === 'Y') {
            return <Text style={[styles.orangeBtn, { marginRight: 10 * scale, marginBottom: 10 * scale }]}
                onPress={() => { navigationSeevice.navigate('OfferSituation', { bidPackageId, isEidt: true, salesType, bizModel, periodNum, periodSeq: this.pageParams.periodSeq, listData: { ...this.props.navigation.state.params } }); }}>成交申请</Text>
        } else if (bizModel === 'Z' && canBargainApply === 'Y') {
            return <Text style={[styles.orangeBtn, { marginRight: 10 * scale, marginBottom: 10 * scale }]}
                onPress={() => { this.props.navigation.navigate(winRule === 'ALL' ? 'WholePackList' : 'NonWholePackList', { bidPackageId, periodNum: this.pageParams.periodNum, salesType }) }}>成交申请</Text>
        }
        return null;
    }

    _renderBottomComponent = (modelItem) => {
        let { resDetail } = this.state;
        let { bizModel, salesType, periodNum, winRule, canRepeatAdd, canBargainApply } = resDetail || {};
        let { status, bidPackageApplyId, applyRemark, createById, bidPackageId, fileIdArry } = modelItem;

        let isLastPeriod = bidPackageApplyId == resDetail.bidPackageApplyId ? true : false;
        //再来一轮新增条件判断
        if (isLastPeriod) {
            isLastPeriod = canRepeatAdd === 'Y' ? true : false;
        }

        //bizModel = 'M';
        //canBargainApply = 'Y'
        console.log("resDetail-999", resDetail);
        let btns = [];
        if (this.pageFrom == 'approve' && bizModel !== 'Z' && bizModel !== 'DD' && (status == '6' || status == '7')) {
            //审批详情底部按钮
            //非招标&&已上架||已下架
            btns = OfferCommon.MODEL_ACTION_BUTTONS[status];

        } else if (this.pageFrom !== 'approve') {
            //资源详情底部按钮
            //M.多轮、Z.招标、P.竞拍、MZ.即买即中、DD.需求判定
            //非发起人不可以操作，只保留查看报盘按钮
            if (this.userInfo.userId !== createById) {
                let sta = status == '6' && (bizModel == 'Z' || bizModel == 'DD') ? '6_ADD_Z' : (status == '6' || status == '7') ? status : '5';
                btns = OfferCommon.MODEL_ACTION_BUTTONS[sta];
            } else {
                btns = OfferCommon.MODEL_ACTION_BUTTONS[status == '6' && (bizModel == 'Z' || bizModel == 'DD') ? '6_ADD_Z' : status == '7' && bizModel == 'M' && isLastPeriod ? '7_ADD_M' : status];
            }
        }
        console.log("btns-99999", btns)
        //审批详情资源包不展示送审备注，无按钮时隐藏按钮栏
        if (this.pageFrom == 'approve' && (!btns || !btns.length)) return;

        return (
            <View style={{ flex: 1, flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 10 * scale }}>
                    {this.pageFrom !== 'approve' ? <Text style={styles.applyRemarkStyle} onPress={() => { this.setState({ remarkModalVisible: true, curApplyRemark: applyRemark }) }}>[送审备注]</Text> : null}
                    {/* <Text style={styles.applyRemarkStyle} onPress={() => { this.getImgView(fileIdArry) }}>[附件]</Text> */}
                </View>
                <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', maxWidth: 190 * scale, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
                    {
                        (btns && btns.length) ? btns.map((item, index) => {
                            return (
                                <Text key={index} style={[item.btnStyle, { marginRight: 10 * scale, marginBottom: 10 * scale }]}
                                    onPress={() => { this._bizModelAction(item, modelItem) }}>{item.text}</Text>
                            )
                        }) : null
                    }
                    {
                        (this.pageFrom !== 'approve') ? this._renderClinch({ salesType, periodNum, winRule, bizModel, canBargainApply, bidPackageId }) : null
                    }
                </View>
            </View >
        )
    }

    _getFirstId = (packageApplyGoodsTOS) => {
        let resultId = null
        packageApplyGoodsTOS && packageApplyGoodsTOS.forEach(item => {
            if (item.isFirstPeriod === 'Y') {
                resultId = item.bidPackageApplyId;
            }
        })
        return resultId;
    }

    render() {
        let { resDetail, status, showRejectModal, remarkModalVisible, curApplyRemark, lightBoxData, statusLit } = this.state;
        let { packageApplyGoodsTOS, tranDesc, salesType, corpId, applyRemark, bizModel, bidPackageId, winRule } = resDetail || {};
        return (
            <ScrollView style={styles.container}>
                <NavigationEvents onWillFocus={async () => {
                    await this.initPage();
                }} />
                {
                    status == 'data' ?
                        <View style={styles.body}>
                            <ResourceBaseInfoCard
                                data={resDetail}
                                titleAction={this.pageFrom === 'approve' ? false : true}
                                copyPress={() => { navigationSeevice.navigate('OfferCreatePage', { salesType, bidPackageApplyId: this._getFirstId(packageApplyGoodsTOS) || resDetail.bidPackageApplyId, corpId, isCopy: true }); }} />
                            {
                                (resDetail.status === '7' && (bizModel === 'M' || bizModel === 'Z')) ? <TouchableOpacity onPress={() => { navigationSeevice.navigate('ClinchRecord', { bizModel, bidPackageId, winRule, salesType, listData: { ...this.props.navigation.state.params } }) }}>
                                    <Text style={styles.ClinchRecord}>【成交记录查询】</Text>
                                </TouchableOpacity> : null
                            }
                            {
                                packageApplyGoodsTOS && packageApplyGoodsTOS.length ?
                                    packageApplyGoodsTOS.map((item, index) => {
                                        return (
                                            <View key={index}>
                                                {this._approvalListItim({ item, index })}
                                            </View>
                                        )
                                    }) : null
                            }
                        </View> : null
                }

                {
                    this.pageFrom === 'approve' ? <View style={styles.baseInfoCard}>
                        <Text style={styles.baseInfoCardTitle}>特别说明：{tranDesc || '-'}</Text>
                        <Text style={styles.baseInfoCardTitle}>送审备注：{applyRemark || '-'}</Text>
                        <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-end', marginTop: 18 * scale }}>
                            <Text style={styles.consent} onPress={() => { this.auditPress(1, resDetail) }}>同意</Text>
                            <Text style={styles.itemdown} onPress={() => { this.auditPress(0, resDetail) }}>驳回</Text>
                        </View>
                    </View> : null
                }
                {
                    status != 'data' ? <View style={{ marginTop: '42%' }}><PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.initPage} /></View> : null
                }
                {
                    statusLit != 'data' ? <View style={{ position: 'absolute', height: '100%', width: '100%' }}><PageStatusIndex status={'loading'} /></View> : null
                }
                <CommonDialog
                    modalVisible={remarkModalVisible}
                    title={'送审备注'}
                    text={curApplyRemark || '-'}
                    onClosePress={() => { this.setState({ remarkModalVisible: false }) }} />

                <RefuseModal
                    titleText={'审批意见'}
                    placeholderText={this.auditResult ? '请输入同意原因' : null}
                    propsDefaultValue={this.auditResult ? '审批同意' : ''}
                    visible={showRejectModal}
                    btnPress={(text) => {
                        this.remark = text;
                        this.approve();
                    }}
                    bgPress={() => {
                        this.setState({
                            showRejectModal: false,
                        });
                    }} />
                {/* 审批流 */}
                <ProgressModal {...lightBoxData} />
                <ModalPicsComponent {...modalPicDelCfg} />
            </ScrollView>
        )
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: style.color.bgGray,
    },
    body: {
        flex: 1,
        backgroundColor: style.color.bgGray
    },
    itemBorder: {
        height: 1 * scale,
        backgroundColor: '#E3E7F0',
        marginBottom: 15 * scale,
    },
    arrowIcon: {
        position: 'absolute',
        right: 0,
        top: 2 * scale,
        right: 32 * scale,
    },
    textRow: {
        marginBottom: 20 * scale
    },
    textRowText: {
        paddingLeft: 15 * scale
    },
    statusSelect: {
        backgroundColor: style.color.gray,
        opacity: 0.7,
        marginTop: 20 * scale,
        marginLeft: 20 * scale,
        padding: 6 * scale,
        width: 94 * scale,
        borderRadius: 20 * scale,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    },
    statusSelectText: {
        fontSize: 13 * scale,
        marginRight: 4 * scale
    },
    statusSelectIcon: {
        width: 10 * scale,
        height: 10 * scale
    },
    baseInfoCard: {
        padding: 12 * scale
    },
    baseInfoCardTitle: {
        marginTop: 10 * scale,
        marginBottom: 12 * scale,
        fontSize: 14 * scale,
        fontWeight: 'bold'
    },
    consent: {
        paddingRight: 20 * scale,
        paddingLeft: 20 * scale,
        paddingTop: 8 * scale,
        paddingBottom: 8 * scale,
        fontSize: 12 * scale,
        opacity: 1,
        color: '#ffffff',
        borderWidth: 1 * scale,
        borderStyle: 'solid',
        borderColor: style.color.themeColor,
        borderRadius: 15 * scale,
        backgroundColor: style.color.themeColor,
        overflow: 'hidden'
    },
    itemdown: {
        fontSize: 12 * scale,
        color: style.color.themeColor,
        paddingRight: 20 * scale,
        paddingLeft: 20 * scale,
        paddingTop: 8 * scale,
        paddingBottom: 8 * scale,
        borderWidth: 1 * scale,
        borderStyle: 'solid',
        borderColor: style.color.themeColor,
        borderRadius: 15 * scale,
        marginRight: 20 * scale,
        marginLeft: 10 * scale,
    },
    applyRemarkStyle: {
        fontSize: 13 * scale,
        color: style.color.themeColor,
        paddingLeft: 14 * scale,
        paddingTop: 8 * scale,
        paddingBottom: 8 * scale
    },
    orangeBtn: {
        paddingRight: 14 * scale,
        paddingLeft: 14 * scale,
        paddingTop: 6 * scale,
        paddingBottom: 6 * scale,
        fontSize: 12 * scale,
        opacity: 1,
        color: '#ffffff',
        borderWidth: 1 * scale,
        borderStyle: 'solid',
        borderColor: '#FA6400',
        borderRadius: 15 * scale,
        backgroundColor: '#FA6400',
        overflow: 'hidden'
    },
    ClinchRecord: {
        fontSize: 14 * scale,
        color: style.color.themeColor,
        fontWeight: 'bold',
        width: '100%',
        textAlign: 'right',
        paddingRight: 16 * scale,
        marginBottom: 10 * scale
    }
})